package com.mzm.ui.admin;

import java.util.List;

import com.mzm.PathUtils;
import com.mzm.api.MzmAdminFacade;
import com.mzm.api.ProductInfoDto;
import com.mzm.api.RecommendationDto;

public class AdminContext implements NodeSelectionListener {
	private MzmAdminFacade mzmAdminFacade;
	private String selectedPath;

	private Integer selectedProductInfoId;

	private ProductListPanel productListPanel;

	private RecommendationsPanel recommendationsPanel;

	public AdminContext() {
	}

	public AdminContext(ProductListPanel productListPanel, RecommendationsPanel recommendationsPanel) {
		this.productListPanel = productListPanel;
		this.recommendationsPanel = recommendationsPanel;
	}

	public MzmAdminFacade getMzmAdminFacade() {
		return mzmAdminFacade;
	}

	public void setMzmAdminFacade(MzmAdminFacade mzmAdminFacade) {
		this.mzmAdminFacade = mzmAdminFacade;
	}

	public String getSelectedPath() {
		return selectedPath;
	}

	public String getSelectedNode() {
		return PathUtils.getLeafNodeName(selectedPath);
	}

	public void setSelectedPath(String selectedPath) {
		this.selectedPath = selectedPath;
	}

	@Override
	public void nodeSelected(String path) {
		this.selectedPath = path;
		List<ProductInfoDto> productInfos = mzmAdminFacade.getProductInfos(path);
		productListPanel.setProductInfos(productInfos);
	}

	public void refreshProductList() {
		if(productListPanel == null) {
			return;
		}
		List<ProductInfoDto> productInfos = mzmAdminFacade.getProductInfos(getSelectedPath());
		productListPanel.setProductInfos(productInfos);
	}

	public void refreshRecommendations() {
		recommendationsPanel.clearRecommendations();
		showRecommendations(selectedProductInfoId);
	}

	public void productSelected(Integer productInfoId) {
		System.out.println("selected product: "+productInfoId);
		this.selectedProductInfoId = productInfoId;
		recommendationsPanel.clearRecommendations();
		showRecommendations(productInfoId);
	}

	private void showRecommendations(Integer productInfoId) {
		List<RecommendationDto> recommendations = mzmAdminFacade.getRecommendations(productInfoId);
		for (int i = 0; i < recommendations.size(); i++) {
			RecommendationDto recommendation = recommendations.get(i);
			recommendationsPanel.showRecommendation("המלצה " + (i + 1), recommendation);
		}
	}

	public Integer getSeletedProductInfoId() {
		return selectedProductInfoId;
	}

}
